﻿using System;

namespace XEvolve.Core.Events
{
    public class ExceptionSafeTopic<EventArguments> : TopicBase<EventArguments> where EventArguments : EventArgs
    {
        private readonly Action<Exception> exceptionHandler;

        private static void NoopHandler(Exception e)
        {
        }

        public ExceptionSafeTopic() : this(NoopHandler)
        {
        }
   
        public ExceptionSafeTopic(Action<Exception> exceptionHandler)
        {
            this.exceptionHandler = exceptionHandler;
        }

        public override void Publish(EventArguments eventArgs)
        {
            foreach (var handler in GetHandlers(eventArgs))
            {
                try
                {
                    handler(eventArgs);
                } catch (Exception e)
                {
                    try
                    {
                        exceptionHandler(e);
                    }catch
                    { 
                    }
                }
            }
        }
    }
}
